package dba.example.guice.interceptors

import grizzled.slf4j.Logging
import org.aopalliance.intercept.MethodInterceptor
import org.aopalliance.intercept.MethodInvocation

class LoggingMethodInterceptor extends MethodInterceptor with Logging {

  override def invoke(invocation: MethodInvocation): Object = {

    val className = invocation.getThis().getClass().getSuperclass().getCanonicalName()
    val methodName = invocation.getMethod().getName()

    try {
      info(String.format("before %s.%s", className, methodName));
      val result = invocation.proceed();
      if (result != null) {
        val returnType = result.getClass().getCanonicalName();
        info(s"after $className.$methodName return type $returnType");
      } else {
        info("after $className.$methodName return type null or void");
      }

      return result;
    } catch {
      case t: Throwable => {
        info("$className.$methodName has thrown ${t.getClass().getCanonicalName()} with message: ${t.getMessage()}");
        throw t;
      }
    }
  }

}
